package org.example.wordcount;

import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;

/**
 * reduce的keyin和valuein是map的keyout和valueout，
 * reduce的keyout和valueout是输出的key和value
 */
public class WordCountReducer extends Reducer<Text, IntWritable, Text, IntWritable> {

    /**
     * 重写reduce方法，实现累加
     * @param key  单词
     * @param values  统计出的次数
     * @param context 上下文
     * @throws IOException
     * @throws InterruptedException
     */
    @Override
    protected void reduce(Text key, Iterable<IntWritable> values, Reducer<Text, IntWritable, Text, IntWritable>.Context context) throws IOException, InterruptedException {
        //声明一个变量来计数
        int count = 0;
        //遍历values，累加次数
        for (IntWritable value : values) {
            //累加次数
            count += value.get();
        }
        //输出
        context.write(key, new IntWritable(count));
    }
}
